<?php

class SiteController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/main';
	
	/**
	 * Declares class-based actions.
	 */
	public function actions()
	{
		return array(
			// captcha action renders the CAPTCHA image displayed on the contact page
			'captcha'=>array(
				'class'=>'CCaptchaAction',
				'backColor'=>0xFFFFFF,
			),
			// page action renders "static" pages stored under 'protected/views/site/pages'
			// They can be accessed via: index.php?r=site/page&view=FileName
			'page'=>array(
				'class'=>'CViewAction',
			),
		);
	}

	/**
	 * This is the default 'index' action that is invoked
	 * when an action is not explicitly requested by users.
	 */
	public function actionIndex($id = null)
	{
		$model = new InputForm;
		$header = ""; 
		$output = "";
		$download = "";
		$footer = ""; 
		$history = new History();
		$save = true;
		
		if (isset($id) && !isset($_POST['InputForm'])) {
			$history_entry = History::model()->find('uuid = :uuid', array('uuid' => $id));

			if ($history_entry) {
				$_POST['InputForm'] = array(
					'body' => $history_entry->body,
					'header' => $history_entry->header,
					'footer' => $history_entry->footer,
					'comment' => $history_entry->comment,
					'number' => 1
				);
				
				Yii::app()->db->createCommand()->update('history', array(
					'loadCount'=>$history_entry->loadCount += 1,
					), 
					'uuid=:id', 
					array(
						':id'=>$history_entry->uuid
					)
				);
				
				$save = false;
			} else {
				Yii::app()->user->setFlash('error', Yii::t('controller', 'Database entry not found'));
			}
		}
		
		if(isset($_POST['InputForm']))
		{
			$uuid = uniqid();
			$model->attributes=$_POST['InputForm'];
			
			if($model->validate()) {
				if ($model->header) {
					$header = $model->header;
					$header = htmlspecialchars($model->header);
					$header .= PHP_EOL;
				}
				
				if ($model->footer) {
					$footer = $model->footer;
					$footer = htmlspecialchars($model->footer);
					$footer .= PHP_EOL;
				}
				
				$downloads = array();
				$endpointData = array();
				
				for ($x = 1; $x <= $model->number; $x++) {
					$proc = new Processor($model->body);
					$tmp = $proc->process();

					$output .= $tmp . PHP_EOL;
					
					$output = htmlspecialchars($output);
					
					if ($model->download) {
						$download .= $tmp . PHP_EOL;
						$downloads[] = $this->saveForDownload($uuid, $model->format, $header . $download . $footer, $x, 'download');
					}
					
					if (isset($model->endpoint) && $model->endpoint != '') {
						$download .= $tmp . PHP_EOL;
						$filename = $this->saveForDownload($uuid, $model->format, $header . $download . $footer, $x, 'tmp');
						$success = $this->saveViaEndpoint($model->endpoint, $filename, 'tmp');
						$this->deleteFile($filename, 'tmp');
						
						if ($success) {
							Yii::app()->user->setFlash('info', Yii::t('controller', 'Data successfully sent to Endpoint'));
						}
					}
				}
				
				$downloadString = '';
				$n = 1;
				foreach ($downloads AS $download) {
					$downloadString .= CHtml::link(Yii::t('controller', '#{n} Download output as file (Right click, Save As)', array('{n}' => $n)),'download/' . $download, array('target' => '_blank')) . '</br>';
					Yii::app()->user->setFlash('info', $downloadString);
					$n++;
				}
				
				$history->uuid      = $uuid;
				$history->user      = Yii::app()->user->getId() ? Yii::app()->user->getId() : 'NULL';
				$history->shared    = Yii::app()->user->getId() ? '0' : '1';
				$history->ip        = $_SERVER['REMOTE_ADDR'];
				$history->header    = $model->header;
				$history->footer    = $model->footer;
				$history->body      = $model->body;
				$history->comment   = $model->comment;
				$history->timestamp = time();
				$history->loadCount = 0;
				
				if ($save) {
					$history->save();
				}
				
				//Clean up the session and remove all entries for the tags
				Yii::app()->session['resetManager']->cleanUp();
			}
		}
		
		$criteria = new CDbCriteria();
		$criteria->limit = "25";
		$criteria->order = "timestamp DESC";
		$history_entries = History::model()->findAll($criteria);
		
		$output = str_replace('---', '<hr>', $output);
		
		$output = $header . $output . $footer;

		$this->render('index',array(
			'model'           => $model,
			'output'          => $output,
			'id'		      => $history->uuid,
			'history_entries' => $history_entries, 
		));
	}
	
	public function actionHistory()
	{
		$model=new History('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['History']))
			$model->attributes=$_GET['History'];

		$this->render('history',array(
			'model'=>$model,
		));
	}

	/**
	 * This is the action to handle external exceptions.
	 */
	public function actionError()
	{
	    if($error=Yii::app()->errorHandler->error)
	    {
	    	if(Yii::app()->request->isAjaxRequest)
	    		echo $error['message'];
	    	else
	        	$this->render('error', $error);
	    }
	}
	
	/**
	 * Displays the login page
	 */
	public function actionLogin()
	{
		$this->pageTitle = Yii::t('title', 'Login');
		
		$model=new LoginForm;

		// if it is ajax validation request
		if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}

		// collect user input data
		if(isset($_POST['LoginForm']))
		{
			$model->attributes=$_POST['LoginForm'];

			// validate user input and redirect to the previous page if valid
			if($model->validate() && $model->login())
				$this->redirect(Yii::app()->user->returnUrl);
		}
		// display the login form
		$this->render('login',array('model'=>$model));
	}

	/**
	 * Logs out the current user and redirect to homepage.
	 */
	public function actionLogout()
	{
		$this->pageTitle = Yii::t('title', 'Logout');
		Yii::app()->user->logout();
		$this->redirect(Yii::app()->homeUrl);
	}
	
	/**
	 * Saves the given output under the given filename
	 * 
	 * @param String $filename the filename under which the output is saved
	 * @param String $output   the output
	 * 
	 * @return boolean
	 */
	public function saveForDownload($filename, $format, $output, $n, $folder)
	{
		if ($format != InputForm::FORMAT_NONE) {
			$filename = 'utd_export_' . str_pad($n, 10, '0', STR_PAD_LEFT) . '_' . $filename . '.' . $format;
		}
		
		$file = fopen($folder . '/' . $filename, 'w');
		fwrite($file, $output);
		fclose($file);
		
		return $filename;
	}
	
	/**
	 * Send the generated data via the given endpoint
	 * 
	 * @param String $id the id of the endpoint
	 * 
	 * @return boolean
	 */
	public function saveViaEndpoint($id, $filename, $folder) {
		$endpoint = Endpoint::model()->findByPk($id);
		
		if ($endpoint->type == 'FTP') {
			$connection_id = ftp_connect($endpoint->url);
			
			$login_result = ftp_login($connection_id, $endpoint->user, $endpoint->password);
			
			if (!$connection_id || !$login_result) {
				return false;
			} else {
				if ($endpoint->folder != '') {
					$ftp = $endpoint->folder . '/' . $filename;
				} else {
					$ftp = $filename;
				}
				
				$saveResult = ftp_put ($connection_id, $ftp, $folder . '/' . $filename, FTP_ASCII);
				if ($saveResult) {
					return true;
				} else {
					return false;
				}
			}
			
			ftp_quit($connection_id);
		}
	}
	
	/**
	 * Deletes the given file in the given folder
	 * 
	 * @param String $filename the name of the file
	 * @param String $folder   the name of the folder
	 * 
	 * @return boolean
	 */
	public function deleteFile($filename, $folder) {
		return unlink($folder . '/' . $filename);
	}
}